const { ccclass, property, menu } = cc._decorator;

@ccclass
@menu('HelloShader/WaveShader')
export default class WaveShader extends cc.Component {

    /** 图片 */
    @property({ type: cc.Sprite, tooltip: '图片' })
    image: cc.Sprite = null;

    /** distance */
    @property({ type: cc.Slider, tooltip: 'distance' })
    disSlider: cc.Slider = null;

    /** distance - label */
    @property({ type: cc.Label, tooltip: 'distance - label' })
    disValue: cc.Label = null;

    /** time */
    @property({ type: cc.Slider, tooltip: 'time' })
    timeSlider: cc.Slider = null;

    /** time - label */
    @property({ type: cc.Label, tooltip: 'time - label' })
    timeValue: cc.Label = null;

    waveStartTime: number = 0.0;

    /** 波移动速度 */
    waveSpeed: number = 0.3;

    start() {
        // this.disSlider.progress = 60 / 100;
        // 计算波纹移动的距离，根据enable到目前的时间*速度求解
        let beginTime = (new Date).getTime() - this.waveStartTime;
        let curWaveDistance: number = beginTime * this.waveSpeed / 1000;

        this.image.getMaterial(0).setProperty('distanceFactor', 60.0);
        this.image.getMaterial(0).setProperty('timeFactor', -30.0);
        this.image.getMaterial(0).setProperty('curWaveDis', curWaveDistance);

        this.addEmitEvent();
    }

    protected update(dt: number): void {
        let beginTime = (new Date).getTime() - this.waveStartTime;
        let curWaveDistance: number = beginTime * this.waveSpeed / 1000;

        if (curWaveDistance > 6.0) return;
        this.image.getMaterial(0).setProperty('curWaveDis', curWaveDistance);
    }

    protected onEnable(): void {
        this.waveStartTime = (new Date()).getTime();
    }

    onDisSlider(slider: cc.Slider, customEventData: string) {
        let progress = slider.progress * 100;
        this.disValue.string = String((progress).toFixed(2));

        this.image.getMaterial(0).setProperty('distanceFactor', progress);
    }

    onTimeSlider(slider: cc.Slider, customEventData: string) {
        let progress = slider.progress;
        this.timeValue.string = String((progress).toFixed(2));

        this.image.getMaterial(0).setProperty('timeFactor', progress);
    }

    onTouchStart(evt: cc.Event.EventTouch) {
        let pos = evt.getLocation();
        let beginTime = (new Date).getTime() - this.waveStartTime;
        let curWaveDistance: number = beginTime * this.waveSpeed / 1000;

        this.image.getMaterial(0).setProperty('distanceFactor', 60.0);
        this.image.getMaterial(0).setProperty('timeFactor', -30.0);
        this.image.getMaterial(0).setProperty('curWaveDis', curWaveDistance);
        this.image.getMaterial(0).setProperty('center', [pos.x / this.node.width, (this.node.height - pos.y) / this.node.height]);
        this.waveStartTime = 0.0;
    }

    addEmitEvent() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
    }
}